<template>
  <div style="margin-top: 30px" class="addForm">
    <el-form ref="form" :model="formData" :rules="rules" label-width="140px" @submit.native.prevent>
      <div v-for="(item, index) in formData.exportData" :key="index">
        <span class="small-title" @click="handleDeleteData(index)">删除该输出数据源组件</span>
        <el-form-item
          label="输出数据源类型"
          :prop="types"
          :rules="{ required: true, message: '不能为空', trigger: 'change' }"
        >
          <el-select
            v-model="item.sourceType"
            placeholder="请选择"
            clearable
            @click.native="visChange(index)"
            @change="(val) => changeType(val, index)"
          >
            <el-option v-for="(i, idx) in options" :key="i.value + idx" :label="i.label" :value="i.value" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="输出数据源"
          :prop="types"
          :rules="{ required: true, message: '不能为空', trigger: 'change' }"
        >
          <el-button icon="el-icon-thumb" @click="handleSelectData(index, item.sourceType)">请选择</el-button>
          <SelectPro
            :ref="'selectRef' + index"
            title="选择接入数据"
            :check-data="item.checkData"
            :qualtable-label="item.qualtableLabel"
            :active="1"
            :source-type="item.sourceType"
            @handleSubmit="(val) => handleSubmit(val, index)"
          />
          <HkTable
            v-if="item.checkData.length > 0"
            :table-data="item.checkData"
            :table-columns="item.qualtableLabel"
            :show-pag="false"
            :operate="true"
          >
            <!--    接入产品    -->
            <template #databaseName="scope">
              {{ JSON.parse(scope.row.connectInfo).databaseName }}
            </template>
            <template #tableName="scope">
              {{ JSON.parse(scope.row.connectInfo).tableName }}
            </template>
            <template #indexName="scope">
              <el-tag>{{ JSON.parse(scope.row.connectInfo).indexName }}</el-tag>
            </template>
            <template #topic="scope">
              <el-tag>{{ JSON.parse(scope.row.connectInfo).topic }}</el-tag>
            </template>
            <template #metaName="scope">
              <el-tag>{{ scope.row.jsonObject.metaName }}</el-tag>
            </template>
            <template #operate="scope">
              <el-button type="text" @click="handleDelete(scope, index)">删除</el-button>
            </template>
          </HkTable>
        </el-form-item>

        <div v-show="item.sourceType == 'JDBC'">
          <el-form-item
            label="输出方式"
            :prop="item.dsMode"
            :rules="{ required: true, message: '不能为空', trigger: 'change' }"
          >
            <el-select v-model="item.dsMode" filterable placeholder="请选择" style="width: 100%" @change="selDsmode">
              <el-option label="直接插入" value="1" />
              <el-option label="删除插入" value="2" />
              <el-option label="更新插入" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-show="item.dsMode == 3"
            label="更新条件"
            :prop="item.dsCondition"
            :rules="{ required: true, message: '不能为空', trigger: 'change' }"
          >
            <el-select v-model="formData.update" placeholder="请选择">
              <el-option v-for="(i, idx) in defaultList" :key="i.value + idx" :label="i.label" :value="i.value" />
            </el-select>
            <hk-table
              :table-data="item.conditions"
              :table-columns="conditionsLabel"
              :operate="true"
              :show-index="true"
              :is-need-index="true"
            >
              <template #condition="scope">
                <el-select v-model="scope.row.row.condition" placeholder="请选择" @change="changeCondition">
                  <el-option v-for="(i, idx) in metaList" :key="i.value + idx" :label="i.label" :value="i.value" />
                </el-select>
              </template>
              <template #operate="scope">
                <el-button
                  v-if="item.conditions.length > 1"
                  type="text"
                  @click="delContion(scope.row.index, index)"
                >删除</el-button>
              </template>
            </hk-table>
            <el-button
              style="border: 1px dashed #2979ff; width: 100%"
              icon="el-icon-plus"
              @click="handleAddRow(index)"
            >新增一行</el-button>
          </el-form-item>
        </div>
      </div>
      <span v-show="options.length > 0" class="small-title" @click="addData">添加输出数据源组</span>
      <el-divider />
      <el-form-item label="选择接入规则" prop="product">
        <el-button icon="el-icon-thumb" @click="selectRules">请选择</el-button>
        <HkTable
          v-if="ruleCheckData.length > 0 && showBottom"
          :table-data="ruleCheckData"
          :table-columns="qualtableRuleLabel"
          :show-pag="false"
          :operate="true"
        >
          <template #operate="scope">
            <el-button type="text" @click="handleDeleteRule(scope, index)">删除</el-button>
          </template>
        </HkTable>
      </el-form-item>
    </el-form>

    <!-- 数据规则部分 -->
    <SelectPro
      :id="id"
      ref="selectRuleRef"
      title="选择接入规则"
      :check-data="ruleCheckData"
      :qualtable-label="qualtableRuleLabel"
      :table-data="tableData"
      :output-data-source-id-list="outputDataSourceIdList"
      @handleSubmit="(val) => handleRuleSubmit(val)"
    />
  </div>
</template>

<script>
import HkTable from '@/components/Hk-Table/index'
import SelectPro from '@/components/Common/selectPro'
import { secondStep, getSecondDetails, updateSecondStep, jdbcConfiguration } from '@/api/milkyway/taskList'
import { getSourceList } from '@/api/milkyway/repositorypage'

export default {
  name: 'Step2',
  components: { HkTable, SelectPro },
  props: {
    //   formData: {
    //     type: Object,
    //     default() {
    //       return {
    // list: [{ region: "", desc: "" }],
    //       };
    //     },
    //   },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      types: '',
      // 返回的数据
      outputDataSourceIdList: [],
      // 是否改变类型
      index: 0,
      // 规则列表的数据
      tableData: [],
      // 是否显示规则列表
      showBottom: false,

      // jdbc默认值
      updateCon: 'data_source_type',
      // 条件组展示数据
      conditionsLabel: [{ label: '新增条件', param: 'condition', type: 'slot' }],
      // 输出数据源展示数据
      qualtableLabel: [],
      qualtableRuleLabel: [
        { label: '名称', param: 'name' },
        { label: '元数据', param: 'metaName' },
        { label: '产品名称', param: 'productName' }
      ],
      // 接入数据源
      checkData: [],
      // 规则数据源
      ruleCheckData: [],
      type: '',

      options: [],
      defaultList: [],
      metaList: [],
      // 表单
      formData: {
        dsMode: undefined,
        dsCondition: undefined,
        rulePolicyId: undefined,
        kafkaList: [],
        jdbcList: [],
        esList: [],
        exportData: [
          {
            qualtableLabel: undefined,
            sourceType: '',
            conditions: [],
            checkData: [],
            dsMode: undefined
          }
        ]
      },

      // 表单参数
      rules: {
        sourceType: { required: true, message: '不能为空', trigger: 'change' },
        dsMode: { required: true, message: '不能为空', trigger: 'change' },
        dsCondition: { required: true, message: '不能为空', trigger: 'change' },
        product: { required: true, message: '不能为空', trigger: 'change' }
      }
    }
  },
  watch: {
    index: {
      handler() {
        // console.log("index", this.index);
        this.optionsList()
        // this.ruleCheckData = [];
      }
    },
    'formData.dsMode': {
      handler(newvalue) {
        if (newvalue == 3) {
          this.jdbcConfiguration()
        }
      },
      deep: true
    },
    id: {
      handler() {
        // this.getSecondDetails(this.id);
      },
      immediate: true
    }
  },
  mounted() {
    this.getProuductType()
    this.getSecondDetails(this.id)
    this.optionsList()
  },
  methods: {
    // 输出方式选择框变化
    selDsmode(val) {
      this.formData.dsMode = val
    },
    jdbcConfiguration() {
      let outPutDataSourceId
      this.formData.exportData.forEach((item) => {
        if (item.sourceType === 'JDBC') {
          outPutDataSourceId = item.checkData[0].id
        }
      })
      jdbcConfiguration({ outPutDataSourceId }).then((res) => {
        this.metaList = res.metaList.map((item) => {
          return {
            label: item.columnName,
            value: item.columnName
          }
        })
        this.defaultList = res.defaultList.map((item) => {
          return {
            label: item.columnName,
            value: item.columnName
          }
        })
      })
    },
    changeCondition() {},
    // 增加条件
    handleAddRow(index) {
      this.formData.exportData[index].conditions.push({
        condition: ''
      })
    },
    // 清空所选项
    visChange(index) {
      return new Promise((resolve, reject) => {
        this.formData.exportData[index].sourceType = ''
        resolve(this.formData.exportData[index].sourceType)
      }).then(() => {
        this.optionsList()
      })
    },
    // 数据源类型选中项变化
    changeType(val, index) {
      this.formData.exportData[index].checkData = []
      this.optionsList()
      this.type = val
      this.ruleCheckData = []
    },
    // 获取options列表
    optionsList() {
      getSourceList({ type: 1 }).then((res) => {
        const options = res.map((item) => {
          return {
            label: item.keyValue,
            value: item.keyValue
          }
        })

        const type = this.formData.exportData.map((item) => {
          return item.sourceType
        })

        this.options = []
        options.forEach((i) => {
          if (type.indexOf(i.value) === -1) {
            if (
              (type.indexOf('JDBC') !== -1 && i.value === 'ES') ||
              (type.indexOf('ES') !== -1 && i.value === 'JDBC')
            ) {
              return
            } else {
              this.options.push(i)
            }
          }
        })
      })
    },
    // 返回值
    handleSubmit(val, index) {
      this.formData.exportData[index].checkData = val
    },
    // 规则的返回值
    handleRuleSubmit(val) {
      this.ruleCheckData = val
      this.showBottom = true
      this.formData.rulePolicyId = val[0].id
    },

    /** 获取类型以及第二步数据 */
    getProuductType() {
      getSourceList({ type: 1 }).then((res) => {
        this.options = res.map((item) => {
          return {
            label: item.keyValue,
            value: item.keyValue
          }
        })
      })
    },

    // 获取第二步数据
    getSecondDetails(id) {
      getSecondDetails(id).then((res) => {
        //  修改样式
        if (res.outDataSourceList) {
          this.formData.exportData = []
          res.outDataSourceList.forEach((item, index) => {
            const arr = []
            const jsonObject = {}
            jsonObject.metaName = item.metaName
            item.jsonObject = jsonObject
            arr.push(item)
            this.formData.exportData.push({
              qualtableLabel: undefined,
              sourceType: item.sourceType,
              conditions: item.dsCondition.split(',').map((i) => {
                return { condition: i }
              }),

              checkData: arr,
              dsMode: item.dsMode
            })
            if (item.sourceType === 'JDBC') {
              this.formData.dsMode = item.dsMode
              this.formData.update = 'data_source_type'
            }
            this.showExportData(index, item.sourceType)
          })
          this.ruleCheckData = []
          this.showBottom = true

          this.formData.rulePolicyId = res.ruleInfo.id
          this.ruleCheckData.push(res.ruleInfo)
          console.log(this.formData)
        }
      })
    },

    /** 提交按钮 */
    submitForm: function() {
      //  保存提交数据
      if (this.$route.params.id) {
        this.getFormData().then(() => {
          if (!this.formData.rulePolicyId || this.formData.rulePolicyId == '') {
            this.$message({
              message: '请选择接入规则',
              type: 'warning'
            })
            return
          }
          updateSecondStep({
            id: this.id,
            taskSaveParamsSourceRule: this.formData
          }).then((res) => {
            this.$message.success('修改成功')
            this.$router.go(-1)
          })
        })
      } else {
        secondStep({
          id: this.id,
          taskSaveParamsSourceRule: this.formData
        }).then((res) => {
          this.$message.success('新增成功')
          this.$router.go(-1)
        })
      }
    },

    // 打开规则选择器
    selectRules() {
      return new Promise((resolve, reject) => {
        this.getFormData().then(() => {
          this.$refs['selectRuleRef'].show(this.ruleCheckData)
        })
      })
    },
    // 格式化数据
    getFormData() {
      return new Promise((resolve, reject) => {
        this.outputDataSourceIdList = []
        this.formData.jdbcList = []
        this.formData.dsCondition = ''
        this.formData.esList = []
        this.formData.kafkaList = []
        console.log(437, this.formData)
        this.formData.exportData.forEach((item) => {
          if (!item.sourceType || item.checkData.length == 0) {
            this.$message({
              message: '有必选项未选',
              type: 'warning'
            })
          } else {
            this.outputDataSourceIdList.push(item.checkData[0].id)
            if (item.sourceType === 'ES') {
              this.formData.esList.push(item.checkData[0].id)
            } else if (item.sourceType === 'Kafka') {
              this.formData.kafkaList.push(item.checkData[0].id)
            } else if (item.sourceType === 'JDBC') {
              this.formData.jdbcList.push(item.checkData[0].id)

              this.formData.dsCondition = item.conditions
                .map((i) => {
                  return i.condition
                })
                .join(',')
            }

            resolve(this.formData)
          }
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete(data, index) {
      this.formData.exportData[index].checkData.splice(0, 1)
      // this.$refs[`selectRef${index}`][0].$refs.table.templateSelection = ''
    },
    handleDeleteRule(data, index) {
      this.ruleCheckData = this.ruleCheckData.splice(index, 1)
      this.formData.rulePolicyId = ''
      // this.$refs.selectRuleRef.$refs.table.templateSelection = ''
    },
    // 删除条件
    delContion(data, index) {
      this.formData.exportData[index].conditions.splice(data, 1)
    },
    handleAddProduct() {
      this.$refs.addRef.isOpen = true
    },
    /**  点击 ‘请选择’ **/
    handleSelectData(index, type) {
      this.showExportData(index, type)
      this.$refs[`selectRef${index}`][0].show(this.formData.exportData[index].checkData)
    },
    // 修改显示的数据
    showExportData(index, type) {
      if (type) {
        this.index = index
        this.type = type

        this.$nextTick(() => {
          if (type === 'Kafka') {
            this.formData.exportData[index].qualtableLabel = [
              { label: '数据源名称', param: 'name' },
              { label: 'IP', param: 'ip' },
              { label: '端口', param: 'port' },
              { label: '主题名', param: 'topic', type: 'slot' }
            ]
          } else if (type === 'ES') {
            this.formData.exportData[index].qualtableLabel = [
              { label: '数据源名称', param: 'name' },
              { label: 'IP', param: 'ip' },
              { label: '端口', param: 'port' },
              { label: '索引名', param: 'indexName', type: 'slot' },
              { label: '数据标准', param: 'metaName', type: 'slot' }
            ]
          } else {
            this.formData.exportData[index].qualtableLabel = [
              { label: '数据源名称', param: 'name' },
              { label: 'IP', param: 'ip' },
              { label: '端口', param: 'port' },
              { label: '数据库名', param: 'databaseName', type: 'slot' },
              { label: '数据表名', param: 'tableName', type: 'slot' },
              { label: '元数据', param: 'metaName', type: 'slot' }
            ]
          }
        })
      }
    },
    /**  关闭弹窗 **/
    handleSelectOpen(value) {
      this.showSelectDialog = value
    },
    /** 添加输出数据源组 **/
    addData() {
      this.formData.exportData.push({
        sourceType: '',
        conditions: [],
        checkData: [],
        dsMode: undefined,
        qualtableLabel: undefined
      })
    },
    // 删除数据组
    handleDeleteData(index) {
      this.formData.exportData.splice(index, 1)
      this.optionsList()
    }
  }
}
</script>

<style scoped>
.small-title {
  display: inline-block;
  cursor: pointer;
  color: #00afff;
  padding: 10px 0;
}
.addForm {
  margin-top: 20px;
  padding: 0 20px;
  height: calc(100% - 90px);
  overflow-y: auto;
}
</style>
